﻿import mx.events.EventDispatcher;
import mx.utils.Delegate;

import com.mixmedia.mx.Event;
import com.mixmedia.mx.AbstractEventDispatcher;

/**
 * @author colin
 */
class com.mixmedia.net.FLVPlayer extends AbstractEventDispatcher{
	private var isPlaying = false;
	private var nowFile = "";
	public var loop = false;

	private var vid_ns:NetStream;
	private var vid_nc : NetConnection;

	public function FLVPlayer(vid:Video){
		vid_nc = new NetConnection();
		vid_nc.connect(null);

		vid_ns = new NetStream(vid_nc);
		vid_ns.setBufferTime(3);
		vid_ns.onStatus = Delegate.create(this, onStreamStatus);

		vid.attachVideo(vid_ns);
		vid.deblocking = 2;
		vid.smoothing = true;
	}

	public function onStreamStatus(evt){
		switch (evt.code){
			case "NetStream.Play.Stop":
				isPlaying=false;
				if(loop==true)vid_ns.seek(0);
				dispatchEvent(new Event(this,Event.COMPLETE));
				break;
			case "NetStream.Play.Start":
				isPlaying = true;
				dispatchEvent(new Event(this,Event.START));
				dispatchEvent(new Event(this,Event.PLAY));
				break;
			case "NetStream.Play.StreamNotFound":
				throw new Error('StreamNotFound');
				break;
			case "NetStream.Buffer.Empty":
				if(evt.bytesLoaded>=evt.bytesTotal){
					isPlaying=false;
					if(loop==true)vid_ns.seek(0);
					dispatchEvent(new Event(this,Event.COMPLETE));					
				};
				break;
		}
	}

	public function load(requestURL:String){
		isPlaying = false;
		nowFile = requestURL;
		vid_ns.play(nowFile);
	}

	public function replay(){
		isPlaying = true;
		vid_ns.seek(0);
		vid_ns.pause(false);
		dispatchEvent(new Event(this,Event.PLAY));
		dispatchEvent(new Event(this,Event.START));
	}


	public function resume(){
		isPlaying = true;
		vid_ns.pause(false);
		dispatchEvent(new Event(this,Event.PLAY));
	}

	public function pause(){
		isPlaying = false;
		vid_ns.pause(true);
		dispatchEvent(new Event(this,Event.STOP));
	}

	public function stop(){
		isPlaying = false;
		vid_ns.close();
		dispatchEvent(new Event(this,Event.STOP));
		dispatchEvent(new Event(this,Event.CLOSE));
	}

	public function pauseAndResume(){
		if(isPlaying==true){
			pause();
		}else{
			resume();
		}
	}
}